﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Co9320.NamaAlert.Server.Parameters;

namespace Co9320.NamaAlert.Server.BackEnd
{
	internal class GetProcess:IDisposable
	{
		private static string ConnStr = Properties.Settings.Default.ConnectionStrings;
		private SqlConnection Con;
		private SqlCommand Cmd;
		private IList<GetParameter> Parameters_;
		private SqlParameter sid, cstr;

		public GetProcess(IList<GetParameter> Parameters)
		{
			if (Parameters == null)
			{
				throw new ArgumentNullException("Parameters");
			}

			Con = new SqlConnection(ConnStr);
			Cmd = Con.CreateCommand();
			sid = new SqlParameter("@sid", System.Data.SqlDbType.NVarChar);
			cstr = new SqlParameter("@cstr", System.Data.SqlDbType.NVarChar);
			Cmd.Parameters.Add(sid);
			Cmd.Parameters.Add(cstr);
			this.Parameters_ = Parameters;

			Cmd.CommandText = "SELECT TagValue FROM GetTagValues(@sid,@cstr);";


		}

		public IList<TagInformation> GetInformation()
		{
			List<TagInformation> infos = new List<TagInformation>();
			Con.Open();
			Cmd.Connection = Con;

			foreach (var element in Parameters_)
			{
				if (Inspection(element))
				{
					TagInformation info = new TagInformation();
					info.StationId = element.StationId;
					info.Caster = element.Caster;

					info.TagValues = GetTags(element);
					infos.Add(info);
				}
				else
				{
					continue;
				}
			}

			Con.Close();
			return infos;
		}

		private bool Inspection(GetParameter element)
		{
			if (element == null)
			{
				return false;
			}

			if (element.Caster == null || element.Caster.Trim().Length == 0)
			{
				return false;
			}

			if (element.StationId == null || element.StationId.Trim().Length == 0)
			{
				return false;
			}

			return true;
		}

		private List<string> GetTags(GetParameter element)
		{
			sid.Value = element.StationId;
			cstr.Value = element.Caster;

			List<string> Ret = new List<string>();

			using(SqlDataReader rdr=Cmd.ExecuteReader())
			{
				while(rdr.Read())
				{
					Ret.Add((string)rdr[0]);
				}
			}

			return Ret;
		}

		#region IDisposable メンバ

		public void Dispose()
		{
			Con.Close();
			Con.Dispose();
			Cmd.Dispose();
		}

		#endregion
	}
}